<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入章节名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="文件标题" prop="title">
            <el-input v-model="queryParams.title" placeholder="请输入文件标题" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['system:File:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['system:File:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['system:File:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['system:File:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" align="center" prop="id" />
          <el-table-column prop="subjectChapterDeptId" label="章节" width="180" align="center">
            <template slot-scope="scope">
              {{ bindChapter(scope.row.subjectChapterDeptId) }}
            </template>
          </el-table-column>
          <el-table-column label="文件标题" align="center" prop="title" />
          <el-table-column label="学习课件" align="center" prop="fileUrl" width="280">
            <template slot-scope="scope">
              <img src="../../../../assets/images/pdf.png" style="width: 40px;height: 40px;"
                @click="gotoPdf(scope.row.fileUrl)" />
              <!-- <File v-if="scope.row.fileUrl !== ''  " v-bind:src="bindFile(scope.row.fileUrl)"
                class="avatar File-avatar" controls="controls">
                您的浏览器不支持文件播放
              </File> -->
            </template>

          </el-table-column>

          <el-table-column label="备注" align="center" prop="remark" />
          <!-- <el-table-column label="" align="center" prop="status" /> -->
          <el-table-column label="操作" align="center" fixed="right" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:File:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:File:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>


    <!-- 添加或修改学习课件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文件标题" />
        </el-form-item>
        <el-form-item label="说明" prop="subTitle">
          <el-input v-model="form.subTitle" placeholder="请输入文件说明" />
        </el-form-item>
        <el-form-item label="文件地址" prop="fileUrl">
          <!-- <el-input v-model="form.fileUrl" type="textarea" placeholder="请输入内容" /> -->
          <el-upload class="avatar-uploader" :action="uploadFileUrl" :on-progress="uploadFileProcess"
            :on-success="handleFileSuccess" :before-upload="beforeUploadFile" :show-file-list="false" :headers="headers">

            <img src="../../../../assets/images/pdf.png" v-if="fileForm.showFilePath !== '' && !fileFlag"
              v-bind:src="fileForm.showFilePath" />
            <i v-else-if="fileForm.showFilePath === '' && !fileFlag" class="el-icon-plus avatar-uploader-icon"></i>
            <el-progress v-if="fileFlag === true" type="circle" v-bind:percentage="fileUploadPercent"
              style="margin-top: 7px"></el-progress>
          </el-upload>
        </el-form-item>
        <el-form-item label="章节" prop="subjectChapterDeptId">
          <treeselect v-model="form.subjectChapterDeptId" :options="deptOptions" :show-count="true" placeholder="请选择章节" />
        </el-form-item>
        <el-form-item label="文件内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <!-- <el-form-item label="任务备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item> -->
        <!-- <el-form-item label="课程" prop="subjectId">
            <el-input v-model="form.subjectId" placeholder="请输入课程" />
          </el-form-item>
          <el-form-item label="专业" prop="subjectDeptId">
            <el-input v-model="form.subjectDeptId" placeholder="请输入专业" />
          </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { listFile, getFile, delFile, addFile, updateFile } from "@/api/course/file";
import Treeselect from "@riophae/vue-treeselect";
import { chapterDeptTreeSelect } from "@/api/course/chapter";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
export default {
  name: "File",
  components: { Treeselect },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload/uploadPdf",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileFlag: false,
      //是否显示进度条
      fileUploadPercent: "",
      //进度条的进度，
      isShowUploadFile: false,
      //显示上传按钮
      fileForm: {
        showFilePath: "", //回显的变量
      },
      // 遮罩层
      loading: true,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 选中数组
      ids: [],
      // 非单个禁用
      deptOptions: [],
      deptName: undefined,
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学习课件表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        subTitle: null,
        fileUrl: null,
        content: null,
        status: null,
        subjectId: null,
        subjectDeptId: null,
        subjectChapterDeptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    gotoPdf(pdfUrl) {
      // window.location.href = pdfUrl
      console.log(this.bindFile(pdfUrl))
      window.open(this.bindFile(pdfUrl))
    },
    bindChapter(id) {
      let courseName = '-';
      console.log(this.deptOptions)
      if (this.deptOptions != undefined  &&this.deptOptions.length>0&& this.deptOptions[0].children != null) {
        this.deptOptions[0].children.forEach(item => {
          if (id == item.id) {
            courseName = item.label
          }
          if (item.children != null) {
            item.children.forEach(item1 => {
              if (id == item1.id) {
                courseName = item.label + '-' + item1.label
              }
              if (item1.children != null) {
                item1.children.forEach(item2 => {
                  courseName = item.label + '-' + item1.label + '-' + item2.label
                })
              }
            })
          }
        })
      }
      return courseName;
    },
    bindFile(url) {
      if (url == null) {
        return null;
      }
      return process.env.VUE_APP_BASE_API + url;
    },
    //上传前回调
    beforeUploadFile(file) {
      var fileSize = file.size / 1024 / 1024 < 1024; //控制大小  修改50的值即可
      if (
        [
          "application/pdf"
        ].indexOf(file.type) === -1 //控制格式
      ) {
        this.$modal.msgError("请上传正确的文件格式");
        return false;
      }
      if (!fileSize) {
        this.$modal.msgError("文件大小不能超过2048M(2G)");
        return false;
      }
      this.isShowUploadFile = false;
    },
    //进度条
    uploadFileProcess(event, file, fileList) {
      //注意在data中添加对应的变量名
      this.fileFlag = true;
      this.fileUploadPercent = file.percentage.toFixed(0) * 1;
    },
    //上传成功回调
    handleFileSuccess(res, file) {
      this.isShowUploadFile = true;
      this.fileFlag = false;
      this.fileUploadPercent = 0;
      console.log(res);
      this.fileForm.showFilePath = process.env.VUE_APP_BASE_API + res.url;
      this.form.fileUrl = res.url;
      this.form.title = res.fileName;
      this.$modal.msgSuccess("上传成功");
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.form.subjectChapterDeptId = data.id;
      this.queryParams.subjectChapterDeptId = data.id;
      this.handleQuery();
    },
    /** 查询科目分类下拉树结构 */
    getDeptTree() {
      chapterDeptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询学习课件列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        subTitle: null,
        fileUrl: null,
        content: null,
        remark: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        status: null,
        subjectId: null,
        subjectDeptId: null,
        subjectChapterDeptId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学习课件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFile(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学习课件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFile(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学习课件编号为"' + ids + '"的数据项？').then(function () {
        return delFile(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/File/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9 !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px !important;
  position: relative !important;
  overflow: hidden !important;
}

.avatar-uploader .el-upload:hover {
  border: 1px dashed #d9d9d9 !important;
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 300px;
  height: 178px;
  display: block;
}
</style>
    